<?php

namespace App\Services\Game\Data\Settlement;

use App\Core\Traits\Numeral;
use App\Exports\Game\Data\Settlement\InfoExport;
use App\Models\Game\Settlement\Detail;
use App\Services\Service;
use App\Services\Traits\DatabaseMysql;
use App\Models\Game\Settlement\Info as SettlementInfo;
use Helper\Timed;
use Ramsey\Uuid\Type\Time;

class InfoService extends Service
{
    use DatabaseMysql, Numeral;

	/**
	 * 导出数据
	 *
	 * @param \Illuminate\Database\Eloquent\Builder $query
	 * @param \Illuminate\Http\Request $request
	 * @param bool $export
	 * @return false|void
	 */
	private function export($query, $request, bool $export)
	{
		if (!$export) {
			return false;
		}
		// 前端排序
		$this->makeOrderParam($request, $query);
		// 第二排序
		$this->makeOrderParam($request, $query, 'id');
		// 平台信息
		$query->with('org:code,name');
		// 导出文件
		InfoExport::query($query)->download();
	}

	/**
	 * 获取数据列表
	 *
	 * @param \Illuminate\Http\Request $request
	 * @param bool $export
	 * @return \Illuminate\Database\Eloquent\Collection[]|int[]|array[]
	 */
	public function getList($request, $export = false)
	{
		$query = SettlementInfo::query();

		// 筛选【平台】
		$this->makeWhereParamOrg($request, $query);
		// 筛选【平台】【排除】
		$this->makeWhereParamNot($request, 'plat_code_exclude', $query, 'plat_code');
		// 筛选【时间】
		$this->makeWhereParamDatetimeTimeZone($request, $query, 'end_time',  'datetime', '' ,'' , 'hour');
		// 筛选【币种】
		$this->makeWhereParam($request, 'currency', $query);
		// 筛选【币种】【排除】
		$this->makeWhereParamNot($request, 'currency_exclude', $query, 'currency');
		// 筛选【状态】
		$this->makeWhereParam($request, 'status', $query);
		// 筛选【类型】
		$this->makeWhereParam($request, 'player_type', $query);
		// 筛选【游戏】
		$this->makeWhereParam($request, 'game_id', $query);
		// 筛选【游戏】【排除】
		$this->makeWhereParamNot($request, 'game_id_exclude', $query, 'game_id');
		// 筛选【场景】
		$this->makeWhereParam($request, 'scene_id', $query);
		// 筛选【搜索】
		$this->makeWhereParamSearch($request, $query);
		// 筛选【字段】
		$this->makeWhereFieldRange($request, $query);
		// 筛选【slo】【旋转类型】
		$this->makeWhereParam($request, 'ext.spin_type', $query);
		// 筛选【slo】【免费游戏】
		$this->makeWhereParamAndNull($request, 'ext.is_free', $query);
		// 筛选【slo】【触发免费游戏】
		$this->makeWhereParamAndNull($request, 'ext.is_free_trigger', $query);
		// 筛选【slo】【触发免费游戏来源】
		$this->makeWhereParam($request, 'ext.free_trigger_source', $query);
		// 筛选【slo】【小游戏】
		$this->makeWhereParamAndNull($request, 'ext.is_bonus', $query);
		// 筛选【slo】【触发小游戏】
		$this->makeWhereParamAndNull($request, 'ext.is_bonus_trigger', $query);

		// 导出数据
		$this->export($query, $request, $export);

		// 数据条数
		$total = (clone $query)->count();
		// 统计数据
		$stats = $this->getStats(clone $query);
		// 排序分页
		$this->makeOrderParam($request, $query)->makePaginationParam($request, $query);
		// 第二排序
		$this->makeOrderParam($request, $query, 'id');
		// 查询数据
		$collection = $query->with('org:code,name')->get();
		$collection = json_decode(json_encode($collection), true);
		foreach ($collection as &$col){
			$col['time_zone'] = Timed::getTimezoneName();

			$detail = Detail::getDetail($col['round_id']);
			if(isset($detail['details']['result']['bet_score']) && !empty($detail['details']['result']['bet_score'])){
				$col['bet_base'] = $detail['details']['result']['bet_score'];
				$col['usd']['bet_base'] = $detail['details']['result']['bet_score'];
			}

		}

		return [
			$collection,
			$total,
			$stats
		];
	}

	/**
	 * 获取统计信息
	 *
	 * @param \Illuminate\Database\Eloquent\Builder $query
	 * @return array
	 */
	private function getStats($query)
	{
		// USD【合计】
		$usd = (clone $query)->getQuery()->selectRaw(implode(',', [
			"IFNULL(CAST(SUM(usd->'$.gain_player') AS DECIMAL({$this->decimals()},{$this->precision()})),0) AS gain_player",
			"IFNULL(CAST(SUM(usd->'$.gain_sys') AS DECIMAL({$this->decimals()},{$this->precision()})),0) AS gain_sys",
			"IFNULL(CAST(SUM(usd->'$.bet_base') AS DECIMAL({$this->decimals()},{$this->precision()})),0) AS bet_base",
			"IFNULL(CAST(SUM(usd->'$.bet_num') AS DECIMAL({$this->decimals()},{$this->precision()})),0) AS bet_num",
		]))->first();
		// USD【RTP】
		$usd['rtp'] = $this->makeRtp($usd['bet_num'], $usd['gain_player']);

		// 分币种【合计】
		$sts = $query->getQuery()->selectRaw(implode(',', [
			'IFNULL(SUM(gain_player),0) as gain_player',
			'IFNULL(SUM(gain_sys),0) as gain_sys',
			'IFNULL(SUM(bet_base),0) as bet_base',
			'IFNULL(SUM(bet_num),0) as bet_num',
			'currency',
		]))
			->groupBy('currency')
			->get();
		// 分币种【RTP】
		$sts->transform(function ($item) {
			return $item + ['rtp' => $this->makeRtp($item['bet_num'], $item['gain_player'])];
		});

		return [
			'usd' => $usd,
			'sts' => $sts,
		];
	}
}
